<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/8/3
 * Time: 1:45 PM
 */

namespace app\zyhsapi\model;


use think\Log;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsFollow extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_follow';

    public $cacheModel = 'user.follow';

    /**
     * @param array $data
     * @return int
     */
    public function SaveData(array $data)
    {
        try
        {
            $id = $this->insertGetId($data);

            $this->listDataAdd($data['uid'], [$data['astr_id'] => $id]);
        }
        catch (\Exception $e)
        {
            Log::write('ZyhsFollow model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            $id = 0;
        }

        return (int)$id;
    }

    public function delData(int $uid, int $astrId)
    {
        try
        {
            $this->where(['uid' => $uid, 'astr_id' => $astrId])->delete();

            $this->listDataDel($uid, [$astrId]);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 获取用户关注信息
     * @param int $uid
     * @param int $page
     * @return array
     * @throws \Exception
     */
    public function userFollowInfo(int $uid, int $page)
    {
        $resData = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->where(['type' => 1, 'uid' => $uid])->order('id ' . $sortType)->column('id', 'astr_id');

                    $resData = [];
                    foreach ($data as $astrId => $id)
                    {
                        $resData[$astrId] = ['id' => $id];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0);

        return $resData;
    }
}
